import React, { useEffect, useRef, useState } from "react";
import "./Home.css";
import Homehead from "./homehead/Homehead";
import "../../mock";
import {
  Table,
  Button,
  Input,
  Select,
  Checkbox,
  Row,
  Col,
  Form,
  Modal,
  message,
} from "antd";
import { connect } from "dva";

function Home(props) {
  const formRef = useRef(null);
  const { dispatch, state } = props;
  const { personList } = state;
  const [open, setOpen] = useState(false);
  const [pageOption, setPageOption] = useState({
    currentPage: JSON.parse(sessionStorage.getItem("page")) || 1,
    pageSize: 10,
  });
  const [selectedRow, setSelectedRow] = useState(null);
  const [messageApi, contextHolder] = message.useMessage();
  const storedQuery = JSON.parse(sessionStorage.getItem("query"));
  const [query, setQuery] = useState(storedQuery || {});

  // 首次渲染，如果列表无数据，异步派发获取
  useEffect(() => {
    if (personList.length === 0) {
      dispatch({ type: "person/fetchData" });
    }
  }, []);

  // 提交修改个人信息
  const onSubmit = async (values) => {
    dispatch({
      type: "person/updatePersonInfo",
      payload: JSON.stringify(values),
    });
    setOpen(false);
    messageApi.open({
      type: "success",
      content: "修改成功！",
    });
  };

  // 修改个人信息的表单
  const PersonInfoForm = ({ open, onSubmit, onCancel }) => {
    const [personForm] = Form.useForm();

    const layout = {
      labelCol: {
        span: 8,
        offset: 0
      },
      wrapperCol: {
        span: 16,
      },
    };

    return (
      <Modal
        open={open}
        title="修改用户信息"
        okText="修改"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          personForm
            .validateFields()
            .then((values) => {
              personForm.resetFields();
              onSubmit(values);
            })
            .catch((info) => {
              console.log("Validate Failed:", info);
            });
        }}
      >
        <Form
          form={personForm}
          {...layout}
          layout="horizontal"
          name="form_in_modal"
          initialValues={
            selectedRow
              ? {
                  id: selectedRow.id,
                  name: selectedRow.name,
                  role: selectedRow.role,
                  skill: selectedRow.skill,
                  address: selectedRow.address,
                }
              : null
          }
        >
          <Form.Item name="id" label="身份id">
            <Input disabled />
          </Form.Item>
          <Form.Item name="name" label="姓名">
            <Input />
          </Form.Item>
          <Form.Item name="role" label="角色">
            <Select placeholder="选择岗位">
              <Select.Option value="前端开发">前端开发</Select.Option>
              <Select.Option value="java开发">java开发</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="skill" label="主要技能">
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地区">
            <Select placeholder="选择地区">
              <Select.Option value="广州">广州</Select.Option>
              <Select.Option value="深圳">深圳</Select.Option>
              <Select.Option value="佛山">佛山</Select.Option>
              <Select.Option value="珠海">珠海</Select.Option>
              <Select.Option value="汕头">汕头</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  // 删除用户
  const handleDelete = async (record) => {
    let { id } = record;
    dispatch({
      type: "person/deletePersonById",
      payload: id,
    });
    messageApi.open({
      type: "success",
      content: "删除成功！",
    });
  };

  // 搜索用户
  const onFinish = async (values) => {
    // 保存搜索条件
    sessionStorage.setItem("query", JSON.stringify(values));

    dispatch({
      type: "person/searchPerson",
      payload: JSON.stringify(values),
    });
  };

  // 重置搜索栏
  const reset = () => {
    sessionStorage.removeItem("query");
    sessionStorage.removeItem("page");
    setPageOption({
      currentPage: 1,
      pageSize: 10,
    });
    setQuery({});
    formRef.current.resetFields();
    dispatch({ type: "person/fetchData" });
  };

  // 表格设置
  const columns = [
    {
      title: "序号",
      dataIndex: "order",
      key: "order",
      render: (text, record, index) =>
        `${(pageOption.currentPage - 1) * pageOption.pageSize + index + 1}`,
    },
    {
      title: "身份id",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
    },
    {
      title: "主要技能",
      dataIndex: "skill",
      key: "skill",
    },
    {
      title: "地区",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "操作",
      dataIndex: "operate",
      key: "operate",
      render: (text, record) => (
        <span>
          {contextHolder}
          <Button
            type="primary"
            onClick={() => {
              setSelectedRow(record);
              setOpen(true);
            }}
          >
            查看详情
          </Button>
          <PersonInfoForm
            open={open}
            onSubmit={onSubmit}
            onCancel={() => {
              setOpen(false);
            }}
          />
          <Button
            type="primary"
            onClick={() => handleDelete(record)}
            style={{ marginLeft: "10px" }}
          >
            删除
          </Button>
        </span>
      ),
    },
  ];
  // 分页设置
  const pageItemRender = (_, type, originalElement) => {
    if (type === "prev") {
      return <Button>上一页</Button>;
    }
    if (type === "next") {
      return <Button>下一页</Button>;
    }
    return originalElement;
  };

  // 页码变化的时候同步更新
  const paginationChange = (page, pageSize) => {
    setPageOption({
      currentPage: page,
      pageSize: pageSize,
    });
    // 保存页码
    sessionStorage.setItem("page", page);
  };

  return (
    <div className="home">
      <div>
        <Homehead />
      </div>
      <div className="manage">
        {/* 顶部搜索栏 */}
        <div className="search-box">
          <Form
            ref={formRef}
            layout="inline"
            onFinish={onFinish}
            initialValues={query}
          >
            <Form.Item label="姓名" name="name">
              <Input />
            </Form.Item>
            <Form.Item label="岗位" name="role">
              <Select
                defaultValue="请选择"
                style={{
                  width: 240,
                }}
                options={[
                  {
                    value: "前端开发",
                    label: "前端开发",
                  },
                  {
                    value: "java开发",
                    label: "java开发",
                  },
                ]}
              />
            </Form.Item>
            <Form.Item label="所在区域" name="address">
              <Checkbox.Group>
                <Row>
                  <Col span={12}>
                    <Checkbox
                      value="广州"
                      style={{
                        lineHeight: "32px",
                      }}
                    >
                      广州
                    </Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox
                      value="深圳"
                      style={{
                        lineHeight: "32px",
                      }}
                    >
                      深圳
                    </Checkbox>
                  </Col>
                </Row>
              </Checkbox.Group>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                onClick={() => {
                  reset();
                }}
                style={{
                  marginLeft: "10px",
                  background: "orange",
                  color: "#fff",
                }}
              >
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>
        {/* 用户列表 */}
        <Table
          bordered={true}
          columns={columns}
          dataSource={personList}
          pagination={{
            showQuickJumper: {
              goButton: <Button style={{ marginLeft: "10px" }}>跳转</Button>,
            },
            itemRender: pageItemRender,
            onChange: paginationChange,
            pageSize: 10,
            current: JSON.parse(sessionStorage.getItem("page")) || 1,
          }}
          rowKey={(personList) => personList.id}
        />
      </div>
    </div>
  );
}

function mapStateToProps(props) {
  return {
    state: props.person,
  };
}

export default connect(mapStateToProps)(Home);
